const https = require('https');
const http = require('http');
const zlib = require('zlib');
const querystring = require('querystring');
const { promisify } = require('util');

// 常量
const windowsappshoptoken = "eyJ0IjoiM2xURVgxaWprdlQ1UjE1eENVZTBQN3M1bWNGTWozbnY5RzRWU3d0VXNyYm5BS0JMYWhCekhpRTd6WDE5MU5BeiIsInYiOjEsInMiOjQsIm0iOjc0Mzg5NTk0OCwidSI6NjM0MTc0Mjh9s";

class CommHelperUtil {
  /**
   * 登录GET请求
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @returns {Promise<{data: string, antiContent: string}>} - 返回响应数据和AntiContent
   */
  static async httpLoginGet(url, strCookie) {
    let retString = "";
    let antiContent = "";

    try {
      // 处理Cookie - 添加时间戳
      strCookie = this.getNewCookie(strCookie);

      // 解析URL
      const urlObj = new URL(url);
      
      // 构建请求选项
      const options = {
        hostname: urlObj.hostname,
        path: urlObj.pathname + urlObj.search,
        method: 'GET',
        headers: {
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cookie': strCookie,
          'Sec-Ch-Ua': 'Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121',
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
          'Accept-Encoding': 'gzip,deflate',
          'Connection': 'keep-alive'
        }
      };

      // 根据不同的客户端设置不同的请求头
      if (strCookie.includes("windows_")) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 PddWorkbench-Online PddBrowser pdd_windows_version/3.4.6.40';
        options.headers['pddid'] = 'fS5jylqF';
        options.headers['windows-app-shop-token'] = windowsappshoptoken;
      } else {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36';
      }

      // 添加Referer
      if (url.includes("commonMallInfo")) {
        options.headers['Referer'] = 'https://mms.pinduoduo.com/mallcenter/changeAccountInfo/accountSetting/accountInfo';
      } else {
        options.headers['Referer'] = 'https://mms.pinduoduo.com/home/';
      }

      // 发送请求并获取响应
      const response = await new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          let chunks = [];
          let responseBody = '';
          
          // 获取Set-Cookie头信息
          if (res.headers['set-cookie']) {
            antiContent = res.headers['set-cookie'].join('; ');
          }

          // 处理响应编码
          const encoding = res.headers['content-encoding'];
          const responseStream = encoding === 'gzip' 
            ? res.pipe(zlib.createGunzip()) 
            : res;

          responseStream.on('data', (chunk) => {
            chunks.push(chunk);
          });

          responseStream.on('end', () => {
            const buffer = Buffer.concat(chunks);
            responseBody = buffer.toString('utf8');
            resolve({ res, body: responseBody });
          });
        });

        req.on('error', (err) => {
          reject(err);
        });

        req.end();
      });

      retString = response.body;
    } catch (ex) {
      console.error('httpLoginGet异常：', ex);
    }

    return { data: retString, antiContent };
  }

  /**
   * 推广登录GET请求
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @returns {Promise<string>} - 返回新的Cookie字符串
   */
  static async httpLoginTuiGuangGet(url, strCookie) {
    let newStrCookie = "";

    try {
      // 更新Cookie时间戳
      strCookie = this.getNewCookie(strCookie);

      const urlObj = new URL(url);
      
      const options = {
        hostname: urlObj.hostname,
        path: urlObj.pathname + urlObj.search,
        method: 'GET',
        headers: {
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cookie': strCookie
        },
        followRedirect: false // 不自动重定向
      };

      // 根据Cookie类型设置请求头
      if (strCookie.includes("windows_")) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.5.58.0 Safari/537.36 PddWorkbench-Online PddBrowser pdd_windows_version/3.4.6.40';
        options.headers['pddid'] = 'fS5jylqF';
        options.headers['windows-app-shop-token'] = windowsappshoptoken;
      } else {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36';
      }

      const response = await new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          // 检查是否是重定向
          if (res.statusCode === 302 || res.statusCode === 301) {
            const location = res.headers.location;
            
            // 处理重定向后的Cookie
            if (res.headers['set-cookie']) {
              const cookies = res.headers['set-cookie'];
              newStrCookie = cookies.join('; ');
            }
          }
          
          let chunks = [];
          res.on('data', (chunk) => {
            chunks.push(chunk);
          });
          
          res.on('end', () => {
            const buffer = Buffer.concat(chunks);
            resolve({ res, body: buffer.toString('utf8') });
          });
        });

        req.on('error', (err) => {
          reject(err);
        });

        req.end();
      });

    } catch (ex) {
      console.error('httpLoginTuiGuangGet异常：', ex);
    }

    return newStrCookie;
  }

  /**
   * 标准GET请求
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @returns {Promise<string>} - 返回响应数据
   */
  static async httpGet(url, strCookie) {
    try {
      // 先获取sessionID
      const jsessionid = await this.buWindowcheckSessioinID(url, strCookie);
      
      const urlObj = new URL(url);
      
      const options = {
        hostname: urlObj.hostname,
        path: urlObj.pathname + urlObj.search,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cookie': strCookie,
          'Connection': 'keep-alive'
        }
      };

      if (strCookie.includes("windows_")) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 PddWorkbench-Online PddBrowser pdd_windows_version/3.4.6.40';
        options.headers['pddid'] = 'fS5jylqF';
        options.headers['windows-app-shop-token'] = "eyJ0IjoiZnUrZlVIdExDQXBqK2g5cDJvd20xNkw2eVVtZEo1VDNoMTFTdXZBMHRqdkFEOTdyMi8zR2lxRGpGTlZMZEM3cSIsInYiOjEsInMiOjQsIm0iOjc0Mzg5NTk0OCwidSI6NjM0MTc0Mjh9";
      } else {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36';
      }

      const response = await new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          let chunks = [];
          
          // 处理响应编码
          const encoding = res.headers['content-encoding'];
          const responseStream = encoding === 'gzip' 
            ? res.pipe(zlib.createGunzip()) 
            : res;

          responseStream.on('data', (chunk) => {
            chunks.push(chunk);
          });

          responseStream.on('end', () => {
            const buffer = Buffer.concat(chunks);
            resolve({ res, body: buffer.toString('utf8') });
          });
        });

        req.on('error', (err) => {
          reject(err);
        });

        req.end();
      });

      return response.body;
    } catch (ex) {
      console.error('httpGet异常：', ex);
      return "";
    }
  }

  /**
   * 带AntiContent的GET请求
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @param {string} antiContent - 安全验证内容
   * @returns {Promise<string>} - 返回响应数据
   */
  static async httpGet2(url, strCookie, antiContent) {
    try {
      const urlObj = new URL(url);
      
      const options = {
        hostname: urlObj.hostname,
        path: urlObj.pathname + urlObj.search,
        method: 'GET',
        headers: {
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cookie': strCookie,
          'Connection': 'keep-alive'
        }
      };

      // 如果有AntiContent，添加到头信息
      if (antiContent) {
        options.headers['Anti-Content'] = antiContent;
      }

      if (strCookie.includes("windows_")) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 PddWorkbench-Online PddBrowser pdd_windows_version/3.4.6.40';
        options.headers['pddid'] = 'fS5jylqF';
        options.headers['windows-app-shop-token'] = windowsappshoptoken;
      } else {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36';
      }

      // 添加Referer
      options.headers['Referer'] = this.getReferer(url);

      const response = await new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          let chunks = [];
          
          // 处理响应编码
          const encoding = res.headers['content-encoding'];
          const responseStream = encoding === 'gzip' 
            ? res.pipe(zlib.createGunzip()) 
            : res;

          responseStream.on('data', (chunk) => {
            chunks.push(chunk);
          });

          responseStream.on('end', () => {
            const buffer = Buffer.concat(chunks);
            resolve({ res, body: buffer.toString('utf8') });
          });
        });

        req.on('error', (err) => {
          reject(err);
        });

        req.end();
      });

      return response.body;
    } catch (ex) {
      console.error('httpGet2异常：', ex);
      return "";
    }
  }

  /**
   * POST请求
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @param {string} postData - POST数据
   * @param {string} antiContent - 安全验证内容
   * @returns {Promise<string>} - 返回响应数据
   */
  static async httpPost(url, strCookie, postData, antiContent) {
    try {
      // 更新Cookie时间戳
      strCookie = this.getNewCookie(strCookie);
      
      const urlObj = new URL(url);
      
      const options = {
        hostname: urlObj.hostname,
        path: urlObj.pathname + urlObj.search,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cookie': strCookie,
          'Connection': 'keep-alive',
          'Content-Length': Buffer.byteLength(postData),
          'Accept-Encoding': 'gzip, deflate, br'
        }
      };

      // 如果有AntiContent，添加到头信息
      if (antiContent) {
        options.headers['Anti-Content'] = antiContent;
      }

      if (strCookie.includes("windows_")) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 PddWorkbench-Online PddBrowser pdd_windows_version/3.4.6.40';
        options.headers['pddid'] = 'fS5jylqF';
        options.headers['windows-app-shop-token'] = windowsappshoptoken;
        options.headers['Etag'] = 'uRWgWvuYEPgIhynWDdKYFqVANZZpAXfh';
      } else {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36';
      }
      
      // 添加Referer
      options.headers['Referer'] = this.getReferer(url);

      const response = await new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          let chunks = [];
          
          // 处理响应编码
          const encoding = res.headers['content-encoding'];
          const responseStream = encoding === 'gzip' 
            ? res.pipe(zlib.createGunzip()) 
            : res;

          responseStream.on('data', (chunk) => {
            chunks.push(chunk);
          });

          responseStream.on('end', () => {
            const buffer = Buffer.concat(chunks);
            resolve({ res, body: buffer.toString('utf8') });
          });
        });

        req.on('error', (err) => {
          reject(err);
        });

        // 写入POST数据
        req.write(postData);
        req.end();
      });

      return response.body;
    } catch (ex) {
      console.error('httpPost异常：', ex);
      return "";
    }
  }

  /**
   * 刷新Token
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @param {object|string} postData - POST数据
   * @param {string} antiContent - 安全验证内容
   * @returns {Promise<string>} - 返回新的Cookie字符串
   */
  static async pddrefreshToken(url, strCookie, postData, antiContent) {
    try {
      // 准备POST数据
      const keyValuePairs = typeof postData === 'string' ? 
        (postData === '{}' ? {} : JSON.parse(postData)) : 
        (postData || {});
      
      // 添加platform参数
      if (strCookie.includes("windows")) {
        keyValuePairs.platform = 0;
      } else {
        keyValuePairs.platform = 0;
      }
      
      const finalPostData = JSON.stringify(keyValuePairs);
      
      const urlObj = new URL(url);
      
      const options = {
        hostname: urlObj.hostname,
        path: urlObj.pathname + urlObj.search,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cookie': strCookie,
          'Accept': '*/*',
          'Cache-Control': 'max-age=0',
          'Accept-Encoding': 'gzip, deflate, br',
          'sec-ch-ua-mobile': '?0',
          'Sec-Fetch-Site': 'same-origin',
          'Sec-Fetch-Mode': 'cors',
          'Sec-Fetch-Dest': 'empty',
          'sec-ch-ua-platform': 'Windows',
          'Upgrade-Insecure-Requests': '1',
          'Connection': 'keep-alive',
          'Content-Length': Buffer.byteLength(finalPostData),
          'Sec-Ch-Ua': 'Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121'
        }
      };

      // 如果有AntiContent，添加到头信息
      if (antiContent) {
        options.headers['Anti-Content'] = antiContent;
      }

      if (strCookie.includes("windows_")) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.5.58.0 Safari/537.36 PddWorkbench-Online PddBrowser pdd_windows_version/3.4.6.40';
        options.headers['pddid'] = 'fS5jylqF';
        options.headers['windows-app-shop-token'] = "eyJ0IjoiZmphVFo1eXAvWWpVY1lEb1l5cXUwbFhwOGJ4Q2NnZnY2aU9oQlhZMTBtNU1pOXJEQnBheTFlbENLNDhya1NvWSIsInYiOjEsInMiOjQsIm0iOjc0Mzg5NTk0OCwidSI6NjM0MTc0Mjh9";
        options.headers['Etag'] = 'rOHh24xqROYbCO8OJq2y3Z86nvbFrqVJ';
      } else {
        options.headers['Etag'] = 'rOHh24xqROYbCO8OJq2y3Z86nvbFrqVJ';
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
      }

      // 添加Origin和Referer
      if (url.includes("mms.pinduoduo.com")) {
        options.headers['Origin'] = 'https://mms.pinduoduo.com';
        options.headers['Referer'] = this.getReferer(url);
      } else if (url.includes("yingxiao")) {
        options.headers['Origin'] = 'https://yingxiao.pinduoduo.com';
        options.headers['Referer'] = this.getReferer(url);
        options.headers['Etag'] = 'ob18wux5kf2ktu';
      }

      // 添加x-visit-time
      options.headers['Cookie'] = strCookie + "x-visit-time=" + this.getvisittime() + ";mms_b84d1838=3523,321,3254,3532,3571,3474,3475,3477,3479,3482,1202,1203,1204,1205,3417,3397";

      const response = await new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          let newStrCookie = '';
          
          // 处理Set-Cookie头
          if (res.headers['set-cookie']) {
            const passid = res.headers['set-cookie'].join(';');
            
            // 解析原始Cookie
            const cookieParts = strCookie.split(';');
            const cookieObj = {};
            
            // 构建Cookie对象
            cookieParts.forEach(part => {
              if (part && part.trim()) {
                const [name, value] = part.trim().split('=');
                if (name && value) {
                  cookieObj[name] = value;
                }
              }
            });
            
            // 处理新的PASSID（如果有）
            if (passid && !passid.includes('uid')) {
              const passidName = passid.split('=')[0];
              newStrCookie += passidName + ';';
            }
            
            // 重建Cookie字符串，排除x-visit-time
            for (const [name, value] of Object.entries(cookieObj)) {
              if (name !== 'x-visit-time') {
                newStrCookie += `${name}=${value};`;
              }
            }
          }

          let chunks = [];
          
          // 处理响应编码
          const encoding = res.headers['content-encoding'];
          const responseStream = encoding === 'gzip' 
            ? res.pipe(zlib.createGunzip()) 
            : res;
            
          responseStream.on('data', (chunk) => {
            chunks.push(chunk);
          });
          
          responseStream.on('end', () => {
            const buffer = Buffer.concat(chunks);
            
            // 尝试解析响应数据
            try {
              // 检查数据类型和格式
              const contentType = res.headers['content-type'] || '';
              
              let responseData;
              
              if (contentType.includes('application/json')) {
                // JSON格式
                responseData = JSON.parse(buffer.toString('utf8'));
              } else if (contentType.includes('text/')) {
                // 文本格式
                responseData = buffer.toString('utf8');
              } else {
                // 尝试检测是否是JSON
                try {
                  responseData = JSON.parse(buffer.toString('utf8'));
                } catch (e) {
                  // 不是JSON，作为普通文本处理
                  responseData = buffer.toString('utf8');
                  // 如果文本包含乱码，则返回base64编码
                  if (responseData.includes('')) {
                    responseData = `[二进制数据] 长度: ${buffer.length} 字节，Base64: ${buffer.toString('base64').slice(0, 100)}...`;
                  }
                }
              }
              
              resolve({
                statusCode: res.statusCode,
                headers: res.headers,
                data: responseData,
                cookie: newStrCookie || null
              });
            } catch (e) {
              // 解析失败，返回原始数据
              resolve({
                statusCode: res.statusCode,
                headers: res.headers,
                data: `[无法解析的数据] ${e.message}`,
                rawData: buffer.toString('base64').slice(0, 100) + '...',
                cookie: newStrCookie || null
              });
            }
          });
        });

        req.on('error', (err) => {
          reject(err);
        });

        // 写入POST数据
        req.write(finalPostData);
        req.end();
      });

      // 返回格式化的响应
      return JSON.stringify(response, null, 2);
    } catch (ex) {
      console.error('pddrefreshToken异常：', ex.message);
      return JSON.stringify({ error: ex.message }, null, 2);
    }
  }

  /**
   * 补充SessionID环境
   * @param {string} url - 请求的URL
   * @param {string} strCookie - Cookie字符串
   * @returns {Promise<string>} - 返回SessionID
   */
  static async buWindowcheckSessioinID(url, strCookie) {
    // 简化版模拟实现，实际可能需要更复杂的逻辑
    return "SESSION_ID_PLACEHOLDER";
  }

  /**
   * 传入Cookie动态变更服务器时间
   * @param {string} cookie - Cookie字符串
   * @returns {string} - 返回更新后的Cookie
   */
  static getNewCookie(cookie) {
    let newCookie = '';
    const now = new Date();
    const milliseconds = now.getTime();
    
    if (!cookie.includes("x-visit-time")) {
      newCookie = cookie + "x-visit-time=" + milliseconds + ";";
    } else {
      const cookieParts = cookie.split(';');
      
      for (let part of cookieParts) {
        if (part && part.trim()) {
          const [name, value] = part.trim().split('=');
          
          if (name === "x-visit-time") {
            newCookie += name + "=" + milliseconds + ";";
          } else if (name && value) {
            newCookie += name + "=" + value + ";";
          }
        }
      }
    }
    
    return newCookie;
  }

  /**
   * 获取当前时间戳
   * @returns {string} - 返回当前时间戳
   */
  static getvisittime() {
    return Date.now().toString();
  }

  /**
   * 获取当前时间戳(备用)
   * @returns {string} - 返回当前时间戳
   */
  static getvisittime2() {
    return (Date.now() - 1000).toString();
  }

  /**
   * 获取Referer
   * @param {string} url - 请求的URL
   * @returns {string} - 返回Referer
   */
  static getReferer(url) {
    if (url.includes("mms.pinduoduo.com")) {
      return "https://mms.pinduoduo.com/home/";
    } else if (url.includes("yingxiao")) {
      return "https://yingxiao.pinduoduo.com/home/";
    }
    return "https://mms.pinduoduo.com/home/";
  }

  /**
   * 将对象转换为字符串
   * @param {object} dict - 需要转换的对象
   * @returns {string} - 返回URL编码的字符串
   */
  static dictionaryToStringData(dict) {
    return querystring.stringify(dict);
  }
}

module.exports = CommHelperUtil; 